﻿using System;
using System.Text;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using Eagles.Base;
using Eagles.Application.Model;
using Eagles.Application.Model.Register;
using Eagles.DomainService.Model.Sms;
using Eagles.Interface.Core.Register;
using Eagles.Interface.Configuration;
using Eagles.Interface.DataAccess.UserInfo;
using Eagles.Interface.DataAccess.SmsAccess;

namespace Eagles.DomainService.Core.Register
{
    public class RegisterHandler: IRegisterHandler
    {
        private readonly IUserInfoAccess userInfoAccess;
        private readonly IEaglesConfig configuration;
        private readonly ISmsAccess smsAccess;

        public RegisterHandler(IUserInfoAccess userInfoAccess, IEaglesConfig configuration, ISmsAccess smsAccess)
        {
            this.userInfoAccess = userInfoAccess;
            this.configuration = configuration;
            this.smsAccess = smsAccess;
        }

        public ValidateCodeResponse GenerateSmsCode(ValidateCodeRequest request)
        {
            var templateCode = "";
            if (string.IsNullOrEmpty(request.Phone) || request.Phone.Length != 11)
                throw new TransactionException(MessageCode.ParametersIsEmpty, MessageKey.ParametersIsEmpty);
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.ParametersIsEmpty, MessageKey.ParametersIsEmpty);
            //校验手机号码是否存在
            if (request.Type == 0)
            {
                templateCode = configuration.EaglesConfiguration.AliyunTemplateCode;
                var result = userInfoAccess.GetPhoneExists(request.Phone);
                if (result != null)
                    throw new TransactionException(MessageCode.ExistsPhone, MessageKey.ExistsPhone);
            }
            else
            {
                templateCode = configuration.EaglesConfiguration.AliyunReferrerTemplateCode;
                var result = userInfoAccess.GetPhoneExists(request.Phone);
                if (result == null)
                    throw new TransactionException(MessageCode.NotExistsPhone, MessageKey.NotExistsPhone);
                if (result.OrgId != request.AppId)
                {
                    throw new TransactionException(MessageCode.NotExistsPhone, MessageKey.NotExistsPhone);
                }
            }
            
            //生成验证码
            var rd = new Random();
            var seq = rd.Next(10, 99);
            var code = rd.Next(1000, 9999);
            var smsConfig = smsAccess.GetSmsConfig(request.AppId);
            if(smsConfig == null)
                throw new TransactionException(MessageCode.ConfigNotExists, MessageKey.ConfigNotExists);
            var sendCount = smsConfig.SendCount;
            var maxCount = smsConfig.MaxCount;
            if (sendCount >= maxCount)
                throw new TransactionException(MessageCode.SendSmsMax, MessageKey.SendSmsMax);
            var smsSendLogLog = new TbSmsSendLog()
            {
                OrgId = request.AppId,
                VendorId = smsConfig.VendorId,
                CreateTime = DateTime.Now,
                Phone = request.Phone
            };
            if (smsConfig.VendorId == configuration.EaglesConfiguration.AliyunVendorId)
            {
                #region 阿里云

                //阿里云
                var product = "Dysmsapi"; //短信API产品名称
                var domain = "dysmsapi.aliyuncs.com"; //短信API产品域名
                var accessKeyId = smsConfig.SginKey;
                var accessKeySecret = smsConfig.AppKey;
                var regionIdForPop = "cn-hangzhou";
                IClientProfile profile = DefaultProfile.GetProfile(regionIdForPop, accessKeyId, accessKeySecret);
                DefaultProfile.AddEndpoint(regionIdForPop, regionIdForPop, product, domain);
                IAcsClient acsClient = new DefaultAcsClient(profile);
                SendSmsRequest sendSmsrequest = new SendSmsRequest();
                try
                {
                    //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                    sendSmsrequest.PhoneNumbers = request.Phone;
                    //必填:短信签名-可在短信控制台中找到
                    sendSmsrequest.SignName = configuration.EaglesConfiguration.AliyunSignName;
                    //必填:短信模板-可在短信控制台中找到
                    sendSmsrequest.TemplateCode = templateCode;
                    //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                    var template = "{\"code\":\"" + code + "\"}";
                    sendSmsrequest.TemplateParam = template;
                    //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                    //sendSmsrequest.OutId = "21212121211";
                    //请求失败这里会抛ClientException异常

                    var requestMsg = new StringBuilder();
                    foreach (var parameters in sendSmsrequest.QueryParameters)
                        requestMsg.AppendFormat("{0}:{1},", parameters.Key, parameters.Value);
                    requestMsg.Remove(requestMsg.ToString().LastIndexOf(','), 1);
                    smsSendLogLog.RequestMsg = requestMsg.ToString();

                    SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(sendSmsrequest);
                    if (sendSmsResponse.Code == "OK")
                        smsSendLogLog.Status = 0;
                    else
                        smsSendLogLog.Status = 1;
                    smsSendLogLog.SmsContent = template;
                    smsSendLogLog.ResponseMsg = sendSmsResponse.Message;
                }
                catch (ServerException e)
                {
                    smsSendLogLog.ResponseMsg = "ServerException" + e.ErrorCode + e.ErrorMessage;
                }
                catch (ClientException e)
                {
                    smsSendLogLog.ResponseMsg = "ClientException" + e.ErrorCode + e.ErrorMessage;
                }

                #endregion
            }
            else if (smsConfig.VendorId == configuration.EaglesConfiguration.BaiduVendorId)
            {
                //百度云
            }
            else if (smsConfig.VendorId == configuration.EaglesConfiguration.TencentVendorId)
            {
                //腾讯云
            }
            else
            {
                throw new TransactionException(MessageCode.ConfigNotExists, MessageKey.ConfigNotExists);
            }
            smsAccess.CreateSmsSendLog(smsSendLogLog); //记录短信日志
            smsAccess.AddSendCount(request.AppId, smsConfig.VendorId); //短信数量+1
            var validateCode = new TbValidCode
            {
                CreateTime = DateTime.Now,
                ValidCode = code,
                Seq = seq,
                OrgId = request.AppId,
                Phone = request.Phone,
                ExpireTime = DateTime.Now.AddMinutes(configuration.EaglesConfiguration.ValidCodeExpireTime)//10分钟后过期
            };
            //塞入数据库
            userInfoAccess.InsertSmsCode(validateCode);

            return new ValidateCodeResponse()
            {
                CodeSeq = seq
            };
        }
    }
}